import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')

  // 根据环境设置不同的配置
  const isDev = command === 'serve'
  const isProd = command === 'build'
  
  return {
    plugins: [react()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    server: {
      port: 3000,
      open: true,
      // 开发环境代理配置
      proxy: isDev ? {
        '/api': {
          target: env.VITE_API_BASE_URL || 'http://localhost:3001',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '/api'),
        },
      } : undefined,
    },
    build: {
      outDir: 'dist',
      sourcemap: mode === 'development',
      // 生产环境优化
      minify: isProd ? 'esbuild' : false,
      rollupOptions: isProd ? {
        output: {
          manualChunks: {
            vendor: ['react', 'react-dom'],
            router: ['react-router-dom'],
            state: ['zustand'],
            http: ['axios'],
          },
        },
      } : undefined,
    },
    // 环境变量前缀
    envPrefix: 'VITE_',
    // 定义全局常量
    define: {
      __APP_ENV__: JSON.stringify(env.VITE_APP_ENV || 'development'),
      __APP_VERSION__: JSON.stringify(env.VITE_APP_VERSION || '1.0.0'),
    },
  }
})
